package com.globefrog.framework.log.util;

import com.globefrog.framework.common.constant.CommonConstants;
import com.globefrog.framework.common.constant.LogConstants;
import com.globefrog.framework.log.ActionLog;
import com.globefrog.framework.log.ActionLogImpl;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;


/**
 * actionLog工具类.
 *
 * @author caijinbang
 * @date 2020-11-08 15:31
 */
public class ActionLogUtils {

  private ActionLogUtils() {

  }

  /**
   * 添加action信息.
   *
   * @param key   键
   * @param value 值
   */
  public static void logParam(String key, String value) {
    ActionLog actionLog = ActionLogImpl.getInstance().currentActionLog();
    if (actionLog != null && value != null) {
      actionLog.logContext(key, value.replaceAll("(\r\n|\r|\n|\n\r)", ""));
    }
  }

  /**
   * 添加业务上下文.
   *
   * @param businessContext 业务上下文
   */
  public static void appendBusiness(String businessContext) {
    String mdcBusinessContext = MDC.get(LogConstants.MDC_BUSINESS_CONTEXT);
    mdcBusinessContext = Optional.ofNullable(mdcBusinessContext).orElse(CommonConstants.SPACE);
    if (StringUtils.isNotEmpty(businessContext)) {
      String newBusinessContext = mdcBusinessContext + businessContext + LogConstants.LOG_SEPARATOR;
      MDC.put(LogConstants.MDC_BUSINESS_CONTEXT, newBusinessContext);
    }
  }
}
